<?php

namespace common\modules\pms\controllers\backend;

use common\components\TreeNodeController;
use common\modules\pms\models\backend\Project;
use common\modules\pms\models\backend\TaskTree;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;

/**
* TaskController implements the CRUD actions for Task model.
*/
class TaskController extends TreeNodeController
{

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();
        $this->defaultPostData = ArrayHelper::merge($this->defaultPostData, [
            'modelClass' => 'common\modules\pms\models\backend\TaskTree',
            'nodeView' => '@common/modules/pms/views/backend/task/node',
        ]);
    }

    /**
     * 查找指定的项目
     *
     * @param int $projectID
     * @return Project
     * @throws \yii\web\BadRequestHttpException
     */
    protected function findProject($projectID)
    {
        /** @var Project $project */
        $project = Project::findOne($projectID);
        if ( ! $project)
        {
            throw new BadRequestHttpException('The requested project not found.');
        }

        return $project;
    }

    /**
     * 首页
     *
     * @param int $project_id
     * @return string
     */
    public function actionIndex($project_id)
    {
        /** @var Project $project */
        $project = $this->findProject($project_id);
        Yii::$app->params[Project::PASS_PROJECT_PARAM] = $project;

        return $this->render('form', [
            'title' => $project->name,
            'project' => $project,
            'treeConfig' => [
                'nodeView' => '@common/modules/pms/views/backend/task/node',
                'query' => TaskTree::find()->where(['project_id' => $project->id])->addOrderBy('root, lft'),
                //'query' => TaskTree::find()->addOrderBy('root, lft'),
                'headingOptions' => ['label' => $project->name],
                'fontAwesome' => true,
                'isAdmin' => false,
                'displayValue' => 1,
                'nodeActions' => [
                    'save' => Url::to(['save', 'project_id' => $project->id]),
                    'manage' => Url::to(['manage', 'project_id' => $project->id]),
                    'remove' => Url::to(['remove', 'project_id' => $project->id]),
                    'move' => Url::to(['move', 'project_id' => $project->id]),
                ],
                'softDelete' => true,
                'cacheSettings' => [
                    'enableCache' => true,
                ],
            ],
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function actionManage()
    {
        /** @var Project $project */
        $project = $this->findProject(Yii::$app->request->get('project_id'));
        Yii::$app->params[Project::PASS_PROJECT_PARAM] = $project;

        return parent::actionManage();
    }
}
